package cn.itsource.service.impl;

import cn.itsource.bean.Employee;
import cn.itsource.bean.Shop;
import cn.itsource.config.PageList;
import cn.itsource.mapper.EmployeeMapper;
import cn.itsource.mapper.ShopMapper;
import cn.itsource.query.ShopQuery;
import cn.itsource.service.IEmployeeService;
import cn.itsource.service.IShopService;
import cn.itsource.util.EmailUtil;
import cn.itsource.util.JsonResult;
import cn.itsource.util.Md5Password;
import cn.itsource.util.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.itsource.util.PetHomeConstant.EMP_STATUS_PENDING;
import static cn.itsource.util.PetHomeConstant.SHOP.*;
import static cn.itsource.util.RedisContants.SHOP_ACTIVE_EMAIL;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-13 16:22:00
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private IEmployeeService employeeService;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public JsonResult getPage(ShopQuery query) {
        //1.获取条件
        String key = query.getKeyword();
        //2.获取原始分页
        Page<Shop> pageKey = new Page<>(query.getPage(),query.getRows());

        //查询条件
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(key),Shop::getName,key);
        if (query.getState()!=null && query.getState()==0){
            queryWrapper.eq(Shop::getState,query.getState());
        }
        Page<Shop> page = this.page(pageKey, queryWrapper);

        //将获取的条件取出
        PageList<Shop> pageList = new PageList<>();
        List<Shop> records = page.getRecords();
        records = records.stream().map(item->{
            Long adminId = item.getAdminId();
            Employee byId = employeeService.getById(adminId);
            if (byId!=null){
                item.setAdminName(byId.getUsername());
            }
            return item;
        }).collect(Collectors.toList());


        pageList.setList(records);
        pageList.setTotal(page.getTotal());

        return JsonResult.success(pageList);
    }

    @Override
    public JsonResult updateState(Shop shop) {
        Shop shopState = this.getById(shop.getId());
        if(shopState.getState()!=null) {
            shopState.setState(shopState.getState().equals(1) ? 0 : 1);
        }else {
            shopState.setState(0);
        }
        boolean byId = this.updateById(shopState);
        if (byId){
            return JsonResult.success();
        }else {
            return JsonResult.error("更新失败");
        }
    }

    /**
     * 商家入驻
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public JsonResult settlement(Shop shop) {
        //1.获取管理员信息
        if (shop==null){
            return JsonResult.error("信息不能为空");
        }
        Employee admin = shop.getAdmin();
        if (admin==null){
            return JsonResult.error("管理员账号信息不能为空");
        }
        //2.校验管理员账号密码
        String username = admin.getUsername();
        if (Strings.isBlank(username)){
            JsonResult.error("密码不能为空");
        }

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        List<Employee> list = employeeService.list(queryWrapper);
        if (list.size()!=0){
            return JsonResult.error("管理员用户名已被注册!");
        }

        String comfirmPassword = admin.getComfirmPassword();
        String password = admin.getPassword();
        if (Strings.isBlank(comfirmPassword)||Strings.isBlank(password)){
            return JsonResult.error("密码或二次密码不能为空格");
        }

        if(comfirmPassword==null||password==null){
            return JsonResult.error("密码或二次密码不能为空");
        }

        //3.验证两次密码
        if (!admin.getComfirmPassword().equals(admin.getPassword())){
            return JsonResult.error("两次密码不一致");
        }

        //3.验证账号密码没问题
        //3.1获取盐值(随机生成一个盐值);
        String salt = UUID.randomUUID().toString().toUpperCase();

        //3.2将密码和盐值作为一个整体加密处理
        String md5Password = Md5Password.getMd5Password(password,salt);

        //4.设置加密后的密码
        admin.setPassword(md5Password);
        //4.1盐值的记录
        admin.setSalt(salt);



        //5将管理的状态设置为待审核
        admin.setState(EMP_STATUS_PENDING);
        //5.1将店铺状态设置为待审核
        shop.setState(SHOP_STATUS_PENDING);



        //6先将admin存入员工表，并获取到id ，存入成功时已成功赋值id
        employeeMapper.insert(admin);
        Long adminId = admin.getId();
        shop.setAdminId(adminId);




        //7.再将shop存入后获取id，且再次赋值给admin的shopid
        shopMapper.insert(shop);
        Long shopId = shop.getId();
        admin.setShopId(shopId);


        //8.更新admin
        employeeService.updateById(admin);


        return JsonResult.success("请求已成功发送，审核会在1-3个工作日内，请注意邮箱查收账户激活邮件！");
    }

    @Override
    public JsonResult settlementAnge(Shop shop) {
        Employee admin = shop.getAdmin();
        //取出邮箱，查询对应的邮箱账户




        return null;
    }

    @Override
    @Transactional
    public JsonResult passShop(Shop shop) {
        //更新店铺状态
        shop.setState(SHOP_STATUS__PASS);
        this.updateById(shop);

        //查询员工中对应shopid的员工

        Long shopId = shop.getId();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getShopId,shopId);
        List<Employee> list = employeeService.list(queryWrapper);
        if (list.size()==0){
            //不存在管理员时,发送邮件二，让店铺重新注册管理员

            return JsonResult.success("店铺不存在管理员");
        }


        //获取到email

        List<String> collect = list.stream().map(item -> {
            String email = item.getEmail();
            return email;
        }).collect(Collectors.toList());

        //将email去重
        HashSet<String> emailSet = new HashSet<>(collect);
        collect.clear();
        for (String e: emailSet
             ) {
           sendPass(e,shopId);
        }
        //返回
        return JsonResult.success("激活验证邮箱发送成功，请注意接收");
    }

    public void sendPass(String email,Long shopId){
        if (!StringUtils.isNotEmpty(email)){
            return ;
        }
        //生成随机六位位随机数
        String code = ValidateCodeUtils.generateValidateCode(6).toString();

        //将随机数拼接到url
        String url = SHOP_EMAIL_URL + code;

        //将验证码存入redis中,设置过期时间为5分钟  key pethome:shop:code: + 6位随机数  value  店铺id
        stringRedisTemplate.opsForValue().set(SHOP_ACTIVE_EMAIL + code, String.valueOf(shopId),5, TimeUnit.MINUTES);

        //调用邮箱发送的工具类完成验证码的发送
        EmailUtil.sendActiveEmail(javaMailSender,url,email);
        log.info("code： {}",code);
    }
}
